package org.example.blog.services.impl;


import org.example.blog.pojo.User;
import org.example.blog.services.IUserService;
import org.example.blog.utils.Constants;
import org.example.blog.utils.CookieUtils;
import org.example.blog.utils.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@Service("permission")
public class PermissionService {

    @Autowired
    private IUserService userService;

    /**
     *
     * 判断是不是管理员
     *
     * @return
     */
    public  boolean admin() {
        // 拿到request 和 response
        ServletRequestAttributes  requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        HttpServletResponse response = requestAttributes.getResponse();
        String tokenKey = CookieUtils.getCookie(request, Constants.User.COOKIE_TOKEN_KEY);
        // 没有令牌的key 等于未登录 不往下执行
        if (TextUtils.isEmpty(tokenKey)) {
            return false;
        }

        User user = userService.checkUser(request, response);
        if (user == null) {
            return false;
        }
        if (Constants.User.ROLE_ADMIN.equals(user.getRoles())) {
            // 管理员
            return true;
        }
        return false;
    }
}
